﻿namespace ScrumLite.WebUx.JsonProxy
{
    using System;
    using System.Collections.ObjectModel;
    using System.Linq;
    using System.Net;
    using System.ServiceModel;
    using System.ServiceModel.Web;
    using ScrumLite.Services;
    using ScrumLite.Services.Contracts;
    using System.Runtime.Serialization;
    using System.Collections.Generic;
    using System.Globalization;

    [ServiceContract(Namespace = "")]
    public class Deliverables
    {
        IDeliverablesService deliverables;

        public Deliverables()
            : this(new LinqDeliverablesService())
        {
        }

        public Deliverables(IDeliverablesService deliverables)
        {
            this.deliverables = deliverables;
        }

        [OperationContract]
        [WebGet(UriTemplate = "GetAll?project={projectId}", ResponseFormat = WebMessageFormat.Json)]
        public DeliverableKeyValue[] GetAll(string projectId)
        {
            Deliverable[] data = this.deliverables.GetDeliverables(projectId);

            List<DeliverableKeyValue> deliverablesValues = new List<DeliverableKeyValue>();

            foreach (Deliverable deliverable in data)
            {
                deliverablesValues.Add(new DeliverableKeyValue { Text = deliverable.FullName, Value = deliverable.Id });
            }

            Deliverables.SetCaching(WebOperationContext.Current, DateTime.Now, 10); // 10 seconds
            return deliverablesValues.ToArray();            
        }

        [OperationContract]
        [WebGet(UriTemplate = "ReadOne?deliverableId={deliverableId}", ResponseFormat = WebMessageFormat.Json)]
        public Deliverable ReadOne(string deliverableId)
        {
            Deliverable data = this.deliverables.GetDeliverable(deliverableId);
            Deliverables.SetCaching(WebOperationContext.Current, DateTime.Now, 10); // 10 seconds
            return data;
        }

        private static void SetCaching(WebOperationContext context, DateTime lastModifiedDate, Int32 maxCacheAge)
        {
            // set CacheControl header
            HttpResponseHeader cacheHeader = HttpResponseHeader.CacheControl;
            String cacheControlValue = String.Format(CultureInfo.InvariantCulture, "max-age={0}, must-revalidate", maxCacheAge);
            context.OutgoingResponse.Headers.Add(cacheHeader, cacheControlValue);

            // set cache validation 
            context.OutgoingResponse.LastModified = lastModifiedDate;
            String tag = context.IncomingRequest.UriTemplateMatch.RequestUri.ToString() + lastModifiedDate.ToString();
            context.OutgoingResponse.ETag = tag;
        }
    }
    [DataContract]
    public class DeliverableKeyValue
    {
        [DataMember]
        public Guid Value { get; set; }

        [DataMember]
        public string Text { get; set; }
    }
}
